package com.luoye.lj.wstool.wsdm;

import com.luoye.lj.wstool.generator.ICodeGenerator;
import com.luoye.lj.wstool.wsdm.entity.WsdtEntity;
import com.luoye.lj.wstool.wsdm.entity.WsdtField;

/*
 * Created with IntelliJ IDEA.
 * User: Dave Liu
 * Date: 2016/4/26
 * Time: 15:43
 * To change this template use File | Settings | File Templates.
 */
public class UpdateSqlCodeGenerator implements ICodeGenerator {
    private WsdtEntity wsdtEntity;

    public UpdateSqlCodeGenerator(WsdtEntity wsdtEntity) {
        this.wsdtEntity = wsdtEntity;
    }
    /*
    update t_temp_info
    set temp_id=#{tempId}
    <if test="tempName !=null and tempName !=''">
            ,temp_name=#{tempName}
    </if>
    <if test="tempStatus !=-1">
            ,temp_state=#{tempStatus}
    </if>
    where
    temp_id=#{tempId}
    */
    @Override
    public String codeGenerate() {
        WsdtField field=null;
        String code="";
        String whereStr="";
        String updateStr="";
        String fixedUpdate="";
        if(this.wsdtEntity!=null){
            if(this.wsdtEntity.getFieldList()!=null){
                for(WsdtField wsdtField:this.wsdtEntity.getFieldList()){
                    if(wsdtField.isPrimary()) {
                        whereStr += "`"+wsdtField.getColumnName()+"`=#{"+wsdtField.getFieldName()+"} and ";
                        fixedUpdate+=",`"+wsdtField.getColumnName()+"`="+wsdtField.getColumnName();
                    }
                    if("int".equals(wsdtField.getFieldType())||"float".equals(wsdtField.getFieldType())||"double".equals(wsdtField.getFieldType())||"short".equals(wsdtField.getFieldType())
                            ||"long".equals(wsdtField.getFieldType())||"byte".equals(wsdtField.getFieldType())){
                        updateStr += " <if test=\""+wsdtField.getFieldName()+" !=-1\">\n" +
                                "            ,`"+wsdtField.getColumnName()+"`=#{"+wsdtField.getFieldName()+"}\n" +
                                "    </if>\n";
                    }else {
                        updateStr += " <if test=\""+wsdtField.getFieldName()+" !=null\">\n" +
                                "            ,`"+wsdtField.getColumnName()+"`=#{"+wsdtField.getFieldName()+"}\n" +
                                "    </if>\n";
                    }
                    field=wsdtField;
                }
            }

            if(!"".equals(whereStr)){
                whereStr=whereStr.substring(0,whereStr.length()-4);
                fixedUpdate=fixedUpdate.substring(1);
            }else{
                whereStr="`"+field.getColumnName()+"`=#{"+field.getFieldName()+"\n";;
                fixedUpdate="`"+field.getColumnName()+"`="+field.getColumnName();
            }
            code+="update "+wsdtEntity.getTableName()+" set "+fixedUpdate+"\n"+updateStr+" where \n"+whereStr;
        }
        return code;
    }
}
